using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using System.Xml.Xsl;
using System.IO;
using System.Reflection;
using System.Xml.XPath;

namespace SPRSS.WebParts
{
    public class RSSRender : System.Web.UI.WebControls.WebParts.WebPart, IWebEditable
    {
        private string rssUrl = "http://blah.winsmarts.com/rss2.aspx";
        private string xslTransform ;

        [Personalizable(true)]
        public string XSLTransform
        {
            get { return xslTransform; }
            set { xslTransform = value; }
        }
	
        [Personalizable(true)]
        public string RssUrl
        {
            get { return rssUrl; }
            set { rssUrl = value; }
        }
	
        public RSSRender()
        {
            this.ExportMode = WebPartExportMode.All;
            TextReader ootbXSLTStream =
                new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "SPRSS.OOTBXSLT.xml"));
            xslTransform = ootbXSLTStream.ReadToEnd();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            XmlDocument rssDoc = new XmlDocument();
            try
            {
                XmlTextReader xRead = new XmlTextReader(rssUrl) ;
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                
                if (rssUrl.StartsWith("/")) // relative url
                {
                    rssUrl = SPContext.Current.Site.Url + rssUrl;
                }

                byte[] rssBytes = wc.DownloadData(rssUrl);
                
                string rssText = System.Text.ASCIIEncoding.ASCII.GetString(rssBytes);
                int xmlIndex = rssText.IndexOf("<");
                rssText = rssText.Substring(xmlIndex);
                rssDoc.LoadXml(rssText);
            }
            catch (Exception ex)
            {
                writer.Write("Feed not available at this time! Error message:<pre>" + ex.ToString()+ "</pre>");
                writer.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                writer.Write("<br/> RSS Url: ");
                writer.Write(rssUrl);
            }
          
            XmlDocument xsltDoc = new XmlDocument();
            xsltDoc.LoadXml(xslTransform);
            
            writer.Write(Transform(rssDoc, xsltDoc));
        }


        private static string Transform(IXPathNavigable input, IXPathNavigable xslt)
        {
            XslCompiledTransform xsltProcessor = new XslCompiledTransform();
            xsltProcessor.Load(xslt);
            Stream results = new MemoryStream();
            if (input is XmlDocument)
            {
                xsltProcessor.Transform(input, null, results);
            }
            results.Position = 0;
            StreamReader rdr = new StreamReader(results);
            return rdr.ReadToEnd();
        }

        #region IWebEditable Members

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new RSSRenderEdit()) ;
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

        #endregion
    }
}
